/** 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.free.i.management;

import it.free.i.naming.CachedNamingProviderProxy;
import it.free.i.naming.NamingBuilder;
import it.free.i.virtual.machine.BootstrapAble;
import it.free.i.virtual.machine.VirtualMachineFactory;
import it.free.i.virtual.machine.hal.LinkingOperationException;
import it.free.i.virtual.machine.hal.devicealias.laboratory.DeviceAliasPortReadClockDaemon;

import java.util.Properties;

import javax.management.JMRuntimeException;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

/** 
 * This class is really a standard one. This is only a delegation pattern
 * @author stefano
 */
public class JmxBootStrapper implements BootstrapAble {

	public static final String DEVICE_MANAGEMENT_JNDI_NAME = "cn=Management";
	private static Logger logger = null;
	private static final String DEVICE_MANAGEMENT_READ_INTERVAL = "jmx.notification.read.interval";
	
	
	static{
		logger = Logger.getLogger(JmxBootStrapper.class);
	}
	
	/**
	 * Made private by the singleton pattern
	 */
	public JmxBootStrapper() {
	}

	
	/**
	 * Activate the devices looking up the jndi properties needed
	 * @throws LinkingOperationException
	 */
	@SuppressWarnings("unchecked")
	public final void boot() throws LinkingOperationException {
		
		String jndiPath = NamingBuilder.buildLookupName(DEVICE_MANAGEMENT_JNDI_NAME, VirtualMachineFactory.CONTEXT);
		Properties managementConfiguration = null;
		
		try{
			logger.info("Device alias management jndi path: [" + jndiPath + "]");
			managementConfiguration = CachedNamingProviderProxy.getInstance().lookUpConfiguration(jndiPath);
			logger.info("Management jndi configuration repository read");

			long readInterval = Long.valueOf(managementConfiguration.getProperty(DEVICE_MANAGEMENT_READ_INTERVAL));
			
			DeviceAliasPortReadClockDaemon.getInstance().setReadInterval(readInterval);
			
			JmxRegisterServer.getInstance().setup(managementConfiguration);
			JmxRegisterServer.getInstance().startRegisterServer();
			
			logger.info("Management subsystem configured");
			
		}catch(NamingException nExc){
			   throw (new LinkingOperationException(nExc));
		}catch(JMRuntimeException jmrExc){
			   throw (new LinkingOperationException(jmrExc));
		}
		
	}
}
